package com.banciyuan.bcywebview.biz.detail.atperson;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AbsListView;
import android.widget.ExpandableListView;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.api.UserApi;
import com.banciyuan.bcywebview.base.activity.BaseActivity;
import com.banciyuan.bcywebview.base.helper.data.UserDataHelper;
import com.banciyuan.bcywebview.base.view.listview.IndexBarView;
import com.banciyuan.bcywebview.biz.detail.SearchPersonActivity;
import com.banciyuan.bcywebview.utils.common.UIUtils;
import com.banciyuan.bcywebview.utils.http.BcyPair;
import com.banciyuan.bcywebview.utils.http.HttpUtils;
import com.banciyuan.bcywebview.utils.http.OnErrorProxy;
import com.banciyuan.bcywebview.utils.http.StringRequestParam;
import com.banciyuan.bcywebview.utils.http.VolleyQueue;
import com.banciyuan.bcywebview.utils.string.StringUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created by hy on 2015/8/14.
 */
public class AtPersonActivity extends BaseActivity implements View.OnClickListener {
    private static final int GOSEARCHPERSON = 102;
    private ExpandableListView eList;
    private IndexBarView assort;
    private RequestQueue mQueue;
    private AtPersonAdapter adapter;
    private List<String> names = new ArrayList<String>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_atperson);
        initArgs();
        initUi();
        initActionbar();
        List<String> personNames =AtPersonProperties.getInstance().getPersonNames();
        if (null == personNames) {
            initData();
        } else {
            names.clear();
            names.addAll(personNames);
            processNamesData();
        }
    }

    @Override
    protected void initUi() {
        eList = (ExpandableListView) findViewById(R.id.elist);
        assort = (IndexBarView) findViewById(R.id.assort);
        View searchView = View.inflate(this, R.layout.discover_group_search_header, null);
        searchView.setBackgroundColor(getResources().getColor(R.color.bg_two));
        TextView tvSearchIntro = (TextView) searchView.findViewById(R.id.tv_search_intro);
        tvSearchIntro.setText(getResources().getString(R.string.search));
        AbsListView.LayoutParams params = new AbsListView.LayoutParams(-1, UIUtils.dip2px(50, this));
        searchView.setLayoutParams(params);
        eList.addHeaderView(searchView);
        searchView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(AtPersonActivity.this, SearchPersonActivity.class);
                intent.putStringArrayListExtra("names", (ArrayList<String>) names);
                startActivityForResult(intent, GOSEARCHPERSON);
            }
        });
//        eList.setAdapter(new TextAdatpter());
        eList.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
            @Override
            public boolean onChildClick(ExpandableListView expandableListView, View view, int groupPosition, int childPosition, long id) {
                String personname = (String) adapter.getChild(groupPosition, childPosition);
                Intent intent = new Intent();
                intent.putExtra("personname", personname + " ");
                setResult(RESULT_OK, intent);
                finish();
                return false;
            }
        });
    }

    @Override
    protected void initArgs() {
        mQueue = VolleyQueue.getRquest(this);
    }

    @Override
    protected void initProgressbar() {
    }

    @Override
    protected void initActionbar() {
        TextView tvTitle = (TextView) findViewById(R.id.base_action_bar_title);
        tvTitle.setText(getResources().getString(R.string.choosefriend));
        findViewById(R.id.base_action_bar_home).setOnClickListener(this);
    }

    @Override
    protected void initAction() {
    }


    @Override
    protected void initData() {
        List<BcyPair> paramsList = new ArrayList<BcyPair>();
        if (UserDataHelper.ifLogin(this))
            paramsList.add(new BcyPair(HttpUtils.TOKEN, UserDataHelper.getInstance(this).getToken()));
        final HashMap<String, String> params = HttpUtils.getData(paramsList);
        String url = HttpUtils.BASE_URL + UserApi.getAtlist();
        Response.Listener succ = new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                JSONObject result = null;
                try {
                    result = new JSONObject(s);
                    Object status = result.get(HttpUtils.UPLOAD_STATUS);
                    String st = status.toString();
                    if (st.equals("1")) {
                        JSONArray array = result.getJSONArray(HttpUtils.UPLOAD_DATA);
                        for (int i = 0; i < array.length(); i++) {
                            JSONObject detail = (JSONObject) array.get(i);
                            String uname = StringUtil.getFromJson(detail, "uname");
                            names.add(uname);
                        }
                        AtPersonProperties.getInstance().setPersonNames(names);
                        processNamesData();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        };

        Response.ErrorListener error = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
            }
        };

        OnErrorProxy errorProxy = new OnErrorProxy(error, succ, url, this, params);
        StringRequestParam stringRequest = new StringRequestParam(Request.Method.POST, url, params, succ, errorProxy);
        mQueue.add(stringRequest);
    }

    private void processNamesData() {
        adapter = new AtPersonAdapter(AtPersonActivity.this, names);
        eList.setAdapter(adapter);
        for (int i = 0, length = adapter.getGroupCount(); i < length; i++) {
            eList.expandGroup(i);
        }
        assort.setOnTouchAssortListener(new IndexBarView.OnTouchAssortListener() {
            public void onTouchAssortListener(String str) {
                if (str.equals("*")) {
                    eList.setSelection(0);
                    return;
                }
                int index = adapter.getAssort().getHashList().indexOfKey(str);
                if (index != -1) {
                    eList.setSelectedGroup(index);
                }
            }

            public void onTouchAssortUP() {
            }
        });
    }

    @Override
    protected void onNetworkError(String result) {
    }

    @Override
    protected Context getContext() {
        return super.getContext();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == GOSEARCHPERSON && resultCode == RESULT_OK) {
            String personname = data.getStringExtra("personname");
            Intent intent = new Intent();
            intent.putExtra("personname", personname + " ");
            setResult(RESULT_OK, intent);
            finish();
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.base_action_bar_home:
                finish();
                break;
        }
    }
}
